package com.sqlcheck.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JsonUtils {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static String mapToJson(Map<String, Object> map) {
        if (map == null || map.isEmpty()) {
            log.warn("mapToJson: map is null or empty");
            return null;
        }
        try {
            String result = objectMapper.writeValueAsString(map);
            log.debug("mapToJson: successfully converted map to JSON: {}", result);
            return result;
        } catch (JsonProcessingException e) {
            log.error("Failed to convert map to JSON", e);
            return null;
        }
    }

    public static Map<String, Object> jsonToMap(String json) {
        if (json == null || json.trim().isEmpty()) {
            log.debug("jsonToMap: json is null or empty, returning empty map. Input: [{}]", json);
            return new HashMap<>();
        }
        try {
            Map<String, Object> result = objectMapper.readValue(json, new TypeReference<Map<String, Object>>() {
            });
            return result;
        } catch (JsonProcessingException e) {
            log.error("Failed to convert JSON to map. Input JSON: [{}]", json, e);
            return new HashMap<>();
        }
    }

    public static <T> String objectToJson(T object) {
        if (object == null) {
            return null;
        }
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            log.error("Failed to convert object to JSON", e);
            return null;
        }
    }

    public static <T> T jsonToObject(String json, Class<T> clazz) {
        if (json == null || json.trim().isEmpty()) {
            return null;
        }
        try {
            return objectMapper.readValue(json, clazz);
        } catch (JsonProcessingException e) {
            log.error("Failed to convert JSON to object", e);
            return null;
        }
    }

    public static <T> String listToJson(java.util.List<T> list) {
        if (list == null || list.isEmpty()) {
            return null;
        }
        try {
            return objectMapper.writeValueAsString(list);
        } catch (JsonProcessingException e) {
            log.error("Failed to convert list to JSON", e);
            return null;
        }
    }

    public static <T> java.util.List<T> jsonToList(String json, Class<T> clazz) {
        if (json == null || json.trim().isEmpty()) {
            return new java.util.ArrayList<>();
        }
        try {
            return objectMapper.readValue(json,
                    objectMapper.getTypeFactory().constructCollectionType(java.util.List.class, clazz));
        } catch (JsonProcessingException e) {
            log.error("Failed to convert JSON to list", e);
            return new java.util.ArrayList<>();
        }
    }

    public static java.util.List<String> parseStringList(String json) {
        return jsonToList(json, String.class);
    }

    public static Map<String, Object> parseMap(String json) {
        return jsonToMap(json);
    }

    public static String toJsonString(Object obj) {
        return objectToJson(obj);
    }

    /**
     * 检查JSON字符串是否有效
     */
    public static boolean isValidJson(String json) {
        if (json == null || json.trim().isEmpty()) {
            return false;
        }
        try {
            objectMapper.readTree(json);
            return true;
        } catch (JsonProcessingException e) {
            return false;
        }
    }

    /**
     * 安全地解析JSON字符串为Map，处理各种异常情况
     */
    public static Map<String, Object> safeParseMap(String json) {
        if (json == null || json.trim().isEmpty() || "null".equals(json.trim())) {
            return new HashMap<>();
        }
        // 尝试解析JSON
        Map<String, Object> result = jsonToMap(json);
        return result != null ? result : new HashMap<>();
    }

    /**
     * 安全地将对象转换为JSON字符串，处理null值
     */
    public static String safeToJsonString(Object obj) {
        if (obj == null) {
            return null;
        }
        String result = objectToJson(obj);
        return result != null ? result : "{}";
    }
}